//
//  ConPublicOldViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/7/20.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConPublicOldViewController.h"
#import "NearPublicInfoCell.h"
#import "OldPublicInfoCell.h"
#import "ClubEditBtnCell.h"
#import "TakePhotoTool.h"
#import "ClubNetwork.h"
#import "MBProgressHUD+MJ.h"
#import "SZLAccountHelper.h"
#import "OldImageDetail.h"
#import "OldActivityDetailModel.h"
#import "ConClubShowViewController.h"
#import "UIViewController+RTRootNavigationController.h"
#import "ConNavigationontroller.h"
#import "ConOldAddImageTextController.h"

@interface ConPublicOldViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;

@end

@implementation ConPublicOldViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑往期";
    if (!self.oldModel) {
        self.oldModel = [[OldActivityDetailModel alloc]init];
    }
    [self setUpView];
    [self setNavi];
}

- (void)setUpView
{
    [self.view addSubview:self.tableView];
    UIButton *addBtn = [[UIButton alloc]initWithFrame:CGRectMake(ScreenW-10-50, ScreenH-64-20-50, 50, 50)];
    [addBtn setTitle:@"＋" forState:UIControlStateNormal];
    addBtn.backgroundColor = [UIColor blueColor];
    [addBtn addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
}
- (void)addClick
{
    ConOldAddImageTextController *addVc = [[ConOldAddImageTextController alloc]init];
    addVc.isAdd = YES;
    __WEAK
    addVc.completeBlock = ^(OldImageDetail *model) {
        [weakSelf.oldModel.detailList addObject:model];
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:addVc animated:YES];
}
- (void)setNavi
{
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    [saveBtn setTitle:@"立即发布" forState:UIControlStateNormal];
    [saveBtn setTitleColor:RGBColor(255, 121, 201) forState:UIControlStateNormal];
    saveBtn.titleLabel.font = Font(16);
    [saveBtn addTarget:self action:@selector(publickClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1+self.oldModel.detailList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 50+ScreenW*125/309.0;
    }
    ClubEditBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubEditBtnCell class])];
    OldImageDetail *desModel = self.oldModel.detailList[indexPath.section-1];
    CGFloat cellH = [cell calculateOldDetailCellHWithModel:desModel];
    return cellH;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OldPublicInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OldPublicInfoCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.oldModel;
        cell.uploadBtnClick = ^(UIButton *btn) {
            [self takePhoto:btn];
        };
        return cell;
    }
    ClubEditBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubEditBtnCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.oldModel = self.oldModel.detailList[indexPath.section-1];
    __WEAK
    cell.editOldBlock = ^(OldImageDetail *model) {
        ConOldAddImageTextController *addVc = [[ConOldAddImageTextController alloc]init];
        addVc.model = model;
        addVc.completeBlock = ^(OldImageDetail *model) {
            [weakSelf.tableView reloadData];
        };
        [weakSelf.navigationController pushViewController:addVc animated:YES];
    };
    cell.deleteOldBlock = ^(OldImageDetail *model) {
        [weakSelf.oldModel.detailList removeObject:model];
        [weakSelf.tableView reloadData];
    };
    return cell;
}
- (void)publickClick
{
    if (!self.oldModel.avatarUrl) {
        [MBProgressHUD showError:@"请补全活动图片"];
        return;
    }
    if (!self.oldModel.title) {
        [MBProgressHUD showError:@"请填写资讯名称"];
        return;
    }
    for (OldImageDetail *model in self.oldModel.detailList) {
        if (!model.dynamicImageContent && (model.dynamicImageList.count == 0)) {
            [MBProgressHUD showError:@"请上传完整的嘉宾信息"];
            return;
        }
    }
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"clubId"] = @(self.clubId);
    parame[@"avatarUrl"] = [NSString stringWithFormat:@"%@",self.oldModel.avatarUrl];
    parame[@"title"] = self.oldModel.title;
    if (self.oldModel.ID) {
        parame[@"id"] = @(self.oldModel.ID);
    }
    NSMutableArray *details = [NSMutableArray array];
    for (OldImageDetail *model in self.oldModel.detailList) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        if (!model.dynamicImageContent) {
            dict[@"dynamicImageContent"] = @"";
        }else {
            dict[@"dynamicImageContent"] = model.dynamicImageContent;
        }
        dict[@"dynamicImage"] = [model.dynamicImageList componentsJoinedByString:@"#"];
        [details addObject:dict];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:details options:0 error:nil];
    parame[@"dynamicList"] = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self showClearBgWaiter];
    [ClubNetwork oldActivityAddModifyWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"发布成功"];
            if (self.publicOldBlock) {
                self.publicOldBlock();
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIViewController *vc = self.rt_navigationController.rt_viewControllers[1];
                if ([vc isKindOfClass:[ConClubShowViewController class]]) {
                    ConClubShowViewController *showVc = (ConClubShowViewController *)vc;
                    if (showVc.refreshBlock) {
                        showVc.refreshBlock(2);
                    }
                }
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
//上传描述图片
- (void)takePhoto:(UIButton *)btn
{
    CGFloat scale = 309/125.0;
    [[TakePhotoTool shareTool]beginSelectWithScale:scale image:^(UIImage *image, NSString *path) {
        [btn setImage:image forState:UIControlStateNormal];
        self.oldModel.avatarUrl = path;
    }];
}
//上传嘉宾
- (void)takeDesPhoto:(UIButton *)upBtn addBtn:(UIButton *)addBtn isHave:(BOOL)isHave model:(OldImageDetail *)model
{
    [[TakePhotoTool shareTool]beginSelectWithScale:1.0 image:^(UIImage *image, NSString *path) {
        [upBtn setBackgroundImage:image forState:UIControlStateNormal];
        model.dynamicImage = path;
        model.avatarImg = image;
        if (isHave) {
            addBtn.enabled = YES;
            addBtn.backgroundColor = RGBColor(255, 120, 201);
        }
    }];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionFooterHeight = 0.01;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OldPublicInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([OldPublicInfoCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ClubEditBtnCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ClubEditBtnCell class])];
    }
    return _tableView;
}

@end
